﻿#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QList>
#include <QObject>
#include <QDebug>
#include <QColor>
#include "changecolor.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    //添加我们的代码
    QObject *pRoot = nullptr;
    QList<QObject*> listObjs = engine.rootObjects();
    int count = listObjs.size();

    for(int i = 0; i<count;i++)
    {
        if(listObjs.at(i)->objectName() == "rootObj")  //qml中Window的对象名称
        {
            pRoot = listObjs.at(i);
            break;
        }
    }

    new ChangeColor(pRoot);

    //C++获取qml的控件
    QObject* pQuitBtn = pRoot->findChild<QObject*>("quitBtn");
    if(pQuitBtn)
    {
        QObject::connect(pQuitBtn, SIGNAL(clicked()), &app, SLOT(quit()));
    }

    QObject *pText = pRoot->findChild<QObject*>("textLabel");
    if(pText)
    {
        bool bRet = QMetaObject::invokeMethod(pText, "setText", Q_ARG(QString, "AAAA"));
        qDebug() << "bRet = " << bRet; //调用失败，没有该方法

        pText->setProperty("color", QColor::fromRgb(255,0,0));
    }

    return app.exec();
}
